package com.chaoxing.controller;

import com.chaoxing.entity.Course;
import com.chaoxing.mapper.CourseMapper;
import com.chaoxing.util.ExcelUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ExcelController {

    @Resource
    private CourseMapper courseMapper;

    //excel导出用户数据
    @GetMapping("/user/export")
    public void exportUser(HttpServletResponse response) {
        List<Course> list = courseMapper.queryCoursePage();
        ExcelUtils.writeExcel(response, Course.class,list);
    }

    //excel批量导入用户数据
    @PostMapping("/course/import")
    @ResponseBody
    public String addUserList(@RequestParam("file") MultipartFile file) {
        try {
            BufferedInputStream in = new BufferedInputStream(file.getInputStream());
            //调用写的一个工具类传入 文件流，所要转换存储的类，以及业务逻辑（我这边直接就是插入语句）
            ExcelUtils.readExcel(in, Course.class,courseMapper);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "ok";
    }

 /*   //批量导入需要先下载模板
    @GetMapping("/download/excel")
    public void downloadExcel(HttpServletResponse response) {
        try(FileInputStream in =new FileInputStream("src\\main\\resources\\用户数据导入模板.xlsx"))  {
            String fileName = "用户数据导入模板";
            //通知浏览器以附件的形式下载处理，设置返回头要注意文件名有中文
            response.setHeader("Content-disposition", "attachment;filename=" +new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while((len = in.read(b)) > 0){
                os.write(b,0,len);
            }
            os.flush();
            os.close();
            in.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
